package com.warehouse.service.impl;

import com.warehouse.entity.ProductCategory;
import com.warehouse.mapper.ProductCategoryMapper;
import com.warehouse.service.ProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品分类Service实现类
 */
@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {
    
    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    
    @Override
    public List<ProductCategory> getAllEnabledCategories() {
        return productCategoryMapper.selectAllEnabled();
    }
    
    @Override
    public List<ProductCategory> getAllCategories() {
        return productCategoryMapper.selectAll();
    }
    
    @Override
    public ProductCategory getCategoryById(Long id) {
        return productCategoryMapper.selectById(id);
    }
    
    @Override
    public ProductCategory getCategoryByName(String categoryName) {
        return productCategoryMapper.selectByCategoryName(categoryName);
    }
    
    @Override
    @Transactional
    public boolean addCategory(ProductCategory category) {
        // 检查分类名称是否已存在
        if (productCategoryMapper.countByCategoryName(category.getCategoryName()) > 0) {
            return false;
        }
        
        // 设置默认值
        if (category.getSortOrder() == null) {
            category.setSortOrder(0);
        }
        if (category.getStatus() == null) {
            category.setStatus(1);
        }
        
        return productCategoryMapper.insert(category) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateCategory(ProductCategory category) {
        // 检查分类名称是否已存在（排除当前记录）
        ProductCategory existingCategory = productCategoryMapper.selectById(category.getId());
        if (existingCategory == null) {
            return false;
        }
        
        // 如果分类名称发生变化，检查是否与其他记录重复
        if (!existingCategory.getCategoryName().equals(category.getCategoryName())) {
            if (productCategoryMapper.countByCategoryName(category.getCategoryName()) > 0) {
                return false;
            }
        }
        
        return productCategoryMapper.update(category) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteCategory(Long id) {
        return productCategoryMapper.deleteById(id) > 0;
    }
    
    @Override
    public boolean isCategoryNameExists(String categoryName) {
        return productCategoryMapper.countByCategoryName(categoryName) > 0;
    }
} 